package net.xiduth.events;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import net.xiduth.game.player.Player;

/**
 * Registers all of the server's game events.
 * 
 * @author Tyluur <ItsTyluur@Gmail.com>
 * @since July 22nd, 2012
 */
public final class EventManager {
	
	/** The map of the button events */
	private static final Map<Integer, ButtonEvent> buttonEvents = new HashMap<Integer, ButtonEvent>();
	
	/** The instance of the logger in this class. */
	private static final Logger logger = Logger.getLogger(EventManager.class.getCanonicalName());
	
	public static final boolean registerEvents() throws Throwable {
		for (File file : new File("./src/net/xiduth/events/button/").listFiles()) {
			if (!((ButtonEvent) Class.forName("net.xiduth.events.button."+ file.getName().replace(".java", "")).newInstance()).init()) {
				return false;
			}
		}
		logger.info("Completed loading " + buttonEvents.size() + " button events.");
		return true;
	}
	
	public static final boolean reloadEvents() throws Throwable {
		buttonEvents.clear();
		return registerEvents();
	}

	public static final boolean handleButtonEvent(Player player,
			int interfaceId, int buttonId, int packetId, int slotId, int slotId2) {
		ButtonEvent event = buttonEvents.get(interfaceId);
		if (event == null) return false;
		return event.handle(player, interfaceId, buttonId, packetId, slotId, slotId2);
	}
	/**
	 * Registers a new {@code ButtonEvent} for an interface id.
	 * 
	 * @param interfaceId
	 *            The interface id.
	 * @param event
	 *            The event to register.
	 * @return {@code True} if succesful.
	 */
	public static boolean register(int interfaceId, ButtonEvent event) {
		if (buttonEvents.containsKey(interfaceId)) {
			logger.info("Button event " + event.getClass().getCanonicalName() + " already registered with " + buttonEvents.get(interfaceId).getClass().getCanonicalName() + ".");
			return false;
		}
		buttonEvents.put(interfaceId, event);
		return true;
	}

}
